package com.gitee.poi.plugin.core.advice;

import com.gitee.poi.plugin.annotations.core.Title;
import com.gitee.poi.plugin.core.advice.ExcelAdvice;
import com.gitee.poi.plugin.model.SheetInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

public class DefaultExcelAdvice implements ExcelAdvice {
    @Override
    public SheetInfo beforeWrite(SheetInfo sheetInfo) {

        Class clazz = sheetInfo.getClazz();
        Title title = (Title) clazz.getAnnotation(Title.class);
        if (title != null) {
            Sheet sheet = sheetInfo.getSheet();
            int rowIndex = sheetInfo.getCurrentRowIndex();
            int columnSpan = sheetInfo.getFields().size() - 1;
            Row titleRow = sheet.createRow(rowIndex);
            Cell titleCell = titleRow.createCell(0);
            CellRangeAddress rangeAddress = new CellRangeAddress(rowIndex, rowIndex, 0, columnSpan);
            sheet.addMergedRegion(rangeAddress);
            CellStyle cellStyle = getStyle(title, sheet);
            titleCell.setCellStyle(cellStyle);
            titleCell.setCellValue(title.value());
            sheetInfo.setCurrentRowIndex(rowIndex + 1);
        }
        return sheetInfo;
    }

    private CellStyle getStyle(Title title, Sheet sheet) {
        CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
        Font font = sheet.getWorkbook().createFont();
        font.setFontName(title.fontName());
        font.setFontHeightInPoints(title.fontSize());
        font.setColor(title.color().getIndex());
        font.setBold(title.bold());
        font.setItalic(title.italic());
        font.setUnderline(title.underline());
        cellStyle.setAlignment(title.align());
        cellStyle.setVerticalAlignment(title.verticalAlign());
        cellStyle.setFont(font);
        return cellStyle;
    }

    @Override
    public SheetInfo afterWrite(SheetInfo sheetInfo) {
        return sheetInfo;
    }
}
